package lib

import (
	"bufio"
	"fmt"
	"log"
	"net"
	"os"
	"os/signal"
	"syscall"

	"github.com/bwmarrin/snowflake"
)

func FatalNotNil(err error)  {
	if err != nil {
		log.Fatal(err)
	}
}

func LogNotnil(err error) {
	if err != nil {
		log.Println(err)
	}
}

func LogMessage(msg ...any)  {
	log.Println(msg...)
}

func PrintMessage(msg ...any)  {
	fmt.Println(msg...)
}

func logConn(id snowflake.ID) func() {
	fmt.Fprintf(os.Stdout, "%d: 已连接\n", id)
	return func() {
		fmt.Fprintf(os.Stdout, "%d: 已断开连接\n", id)
	}
}

func HandleConnection(conn net.Conn, id snowflake.ID, handleMsg func(string), close func())  {
	defer logConn(id)()

	defer close()

	scanner := bufio.NewScanner(conn)

	scanner.Split(bufio.ScanLines)

	for scanner.Scan() {
		bytes := scanner.Bytes()
		if len(bytes) > 0 {
			handleMsg(string(bytes))
		}
	}

	LogNotnil(scanner.Err())
}

func SignalHandler() {
	sigchan := make(chan os.Signal, 1)

	signal.Notify(sigchan, os.Interrupt)
	signal.Notify(sigchan, syscall.SIGALRM)

	<-sigchan

	defer os.Exit(0)
}